package cn.edu.huanu.controller;

import cn.edu.huanu.exception.BusinessException;
import cn.edu.huanu.pojo.User;
import cn.edu.huanu.service.UserService;
import cn.edu.huanu.service.impl.UserServiceImpl;
import cn.edu.huanu.utils.JsonUtils;
import cn.edu.huanu.utils.R;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author hb
 * @date 2025-11-06 11:44:07
 */
@WebServlet("*.user")
public class UserManagerAction  extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        String servletPath = req.getServletPath();
        //提供业务层的实现
        UserService userService=new UserServiceImpl() ;
        PrintWriter out = resp.getWriter();

        if("/login.user".equals(servletPath)){
            String reqData = req.getReader().readLine();
            System.out.println("服务器处理："+reqData);
            //将JSON格式的字符串转成java对象
            User reqUser = JsonUtils.jsonToPojo(reqData, User.class);
            //根据request中的sessionid获得Session对象。如果sessionid不存在则创建新的session对象
            HttpSession session = req.getSession();
            R r=new R();
            try{
                User user = userService.login(reqUser.getUsername(), reqUser.getPassword());
                session.setAttribute("user",user);

                r.success().setData(user);

            } catch (BusinessException e) {
                r.error().setMessage(e.getMessage());
            }
            out.println(JsonUtils.objectToJson(r));
        }else if("/checkusername.user".equals(servletPath)){
            //fecth提交的数据不能使用表单的形式获得数据
            //String username = req.getParameter("username");

            String reqData = req.getReader().readLine();
            System.out.println("服务器处理："+reqData);
            //将JSON格式的字符串转成java对象
            User user = JsonUtils.jsonToPojo(reqData, User.class);

            R r=userService.checkUserNameExist(user.getUsername());
            out.println(JsonUtils.objectToJson(r));
        }else if("/regist.user".equals(servletPath)){
            String reqData = req.getReader().readLine();
            System.out.println("服务器处理："+reqData);
            //将JSON格式的字符串转成java对象
            User user = JsonUtils.jsonToPojo(reqData, User.class);
            R r=  userService.regiester(user);
            out.println(JsonUtils.objectToJson(r));

        }
    }
}
